<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            :clickModalClose="true"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">
                <!--加一个联系人下拉-->
                <el-form-item label="联系人" prop="contactPerson">
                    <el-select v-model="formData.contactPerson" clearable placeholder="请选择站点联系人" style="width: 240px">
                        <el-option v-for="item in dictData.sites" :key="item.id" :label="item.nickname"
                                   :value="item.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="APP用户组" prop="groupIds">
                    <el-select v-model="formData.groupIds" multiple placeholder="请选择用户组" style="width: 240px">
                        <el-option v-for="group in dictData.groups" :key="group.id" :label="group.name"
                                   :value="group.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属角色" prop="roleIds">
                    <el-select v-model="formData.roleIds" multiple placeholder="所属角色" style="width: 240px">
                        <el-option v-for="item in dictData.roles" :key="item.id" :label="item.name" :value="item.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="站点名称" prop="siteName">
                    <el-input v-model="formData.siteName" placeholder="请输入站点名称"/>
                </el-form-item>
                <el-form-item label="站点经度" prop="longitude">
                    <el-input v-model="formData.longitude" placeholder="请输入站点经度"/>
                </el-form-item>
                <el-form-item label="站点纬度" prop="latitude">
                    <el-input v-model="formData.latitude" placeholder="请输入站点纬度"/>
                </el-form-item>
                <el-form-item label="所在地区" prop="streetId">
                    <el-tree-select
                        class="flex-1"
                        v-model="formData.streetId"
                        :data="optionsData.areaLevel"
                        clearable
                        node-key="id"
                        :props="{
                            value: 'id',
                            label: 'name',
                            disabled(data: any) {
                                return !!data.isStop
                            }
                        }"
                        :default-expand-all="true"
                        placeholder="请选择区域"
                    />
                </el-form-item>
                <el-form-item label="站点地址" prop="siteAddress">
                    <el-input v-model="formData.siteAddress" placeholder="请输入站点详细地址"/>
                </el-form-item>
                <el-form-item label="站点排序" prop="siteSorting">
                    <el-input-number v-model="formData.siteSorting"/>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type {FormInstance} from 'element-plus'
import {siteEdit, siteAdd, siteDetail, siteManager, areaLevel, userAdminSite, roleAll} from '@/api/site'
import {groupAll} from '@/api/usergroup'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type {PropType} from 'vue'
import {fetchSiteList} from "@/api/devicebysite";
import Regional from '@/Regional.json'
import {useDictOptions} from "@/hooks/useDictOptions";

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})

const { optionsData } = useDictOptions<{
    areaLevel: any[]
}>({
    areaLevel: {
        api: areaLevel
    }
})

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑站点' : '新增站点'
})
const userids = ref([]) //pc负责人

const formData = reactive({
    id: '',
    administratorId: [],
    siteName: '',
    longitude: null,
    latitude: null,
    siteAddress: '',
    streetId: '',
    userids: [],
    contactPerson: [], //站点联系人
    roleIds: [], //所选站点角色
    siteSorting: 0,
    groupIds: []
})

const formRules = {
    address: [
        {
            required: true,
            message: '请选择所在地区',
            trigger: ['change']
        }
    ],
    id: [
        {
            required: true,
            message: '请输入站点id',
            trigger: ['blur']
        }
    ],
    administratorId: [
        {
            required: true,
            message: '请输入站点负责人',
            trigger: ['blur']
        }
    ],
    groupIds: [
        {
            required: true,
            message: '请输入用户组',
            trigger: ['blur']
        }
    ],
    siteName: [
        {
            required: true,
            message: '请输入站点名称',
            trigger: ['blur']
        }
    ],
    longitude: [
        {
            required: true,
            message: '请输入站点经度',
            trigger: ['blur']
        }
    ],
    latitude: [
        {
            required: true,
            message: '请输入站点纬度',
            trigger: ['blur']
        }
    ],
    contactPerson: [
        {
            required: true,
            message: '请输入站点联系人',
            trigger: ['blur']
        }
    ],
    roleIds: [
        {
            required: true,
            message: '请选择站点所属角色',
            trigger: ['blur']
        }
    ],
    siteSorting: [
        {
            required: true,
            message: '请输入站点排序,数值越大越靠前',
            trigger: ['blur']
        }
    ],
}

// //存放站点数据
const dictData = reactive({
    sites: [],  // 存储站点名称数据
    addressList: Regional, // 存储省市县数据
    options: [], //pc负责人
    roles: [],//所有角色
    groups: []
});
// //设置站点数据
onMounted(async () => {
    dictData.sites = await siteManager(); // 调用后端接口获取站点数据，并赋值给dictData.sites
    dictData.options = await userAdminSite();
    dictData.roles = await roleAll();
    dictData.groups = await groupAll();
});

const handleChange = async (value) => {
    formData.streetId = value[0]
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    const data: any = {...formData}
    mode.value == 'edit' ? await siteEdit(data) : await siteAdd(data)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }


}

const getDetail = async (row: Record<string, any>) => {
    const data = await siteDetail({
        id: row.id
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
